<?php
if (session_id() == '') {
    @session_start();
}
function captchaSettings() {
    $width = 200;
    $height = 75;
    $maxCodeLength = 5;
    $backgroundColor = array(255, 255, 255);
    $borderColor = array(128, 128, 128);
    $colors = array(array(128, 64, 192), array(192, 64, 128), array(108, 192,
            64));
    $font = pathinfo(__FILE__, PATHINFO_DIRNAME) . '/arial.ttf';
    $linesNumber = 1000;
    return array($width, $height, $maxCodeLength, $backgroundColor,
            $borderColor, $colors, $font, $linesNumber);
}

function prepareImage($width, $height, $backgroundColor, $borderColor,
        $colors) {
    $image = imagecreatetruecolor($width, $height);
    $background = imagecolorallocate($image, $backgroundColor[0],
            $backgroundColor[1], $backgroundColor[2]);
    $border = imagecolorallocate($image, $borderColor[0], $borderColor[1],
            $borderColor[2]);
    foreach ($colors as &$color) {
        $color = imagecolorallocate($image, $color[0], $color[1], $color[2]);
    }
    return array($image, $background, $border, $colors);
}

function prepareCanvas($image, $width, $height, $background, $border) {
    imagefilledrectangle($image, 1, 1, $width - 2, $height - 2, $background);
    imagerectangle($image, 0, 0, $width - 1, $height - 1, $border);
}

function drawText($image, $text, $colors, $font, $width, $maxCodeLength) {
    $length = strlen($text);
    $numColors = count($colors);
    $textLength = min(array(strlen($text), $maxCodeLength));
    $characterSpace = $width / ($textLength + 1);
    for ($i = 0; $i < $length; $i++) {
        $color = $colors[$i % $numColors];
        imagettftext($image, 28 + rand(0, 8), -20 + rand(0, 40),
                ($i + 0.3) * $characterSpace, 50 + rand(0, 10), $color, $font,
                $text{$i});
    }
}

function drawLines($image, $width, $height, $number, $colors) {
    $numColors = count($colors);
    for ($i = 0; $i < $number; $i++) {
        $x1 = rand(5, $width - 5);
        $y1 = rand(5, $height - 5);
        $x2 = $x1 + rand(-4, 4);
        $y2 = $y1 + rand(-4, 4);
        imageline($image, $x1, $y1, $x2, $y2, $colors[$i % $numColors]);
    }
}

function generateCaptchaCode($maxCodeLength) {
    require_once dirname(__FILE__) . '/../../config.php';
    list($userpassword, $serverport) =
            splitString(Config::DATABASE_ACCESS, '@');
    list($user, $password) = splitString($userpassword, ':');
    list($serverport, $dbname) = splitString($serverport, '//');
    list($server, $port) = splitString($serverport, ':');
    mysql_connect($server, $user, $password);
    mysql_select_db($dbname);
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRSTUVWXYZ0123456789';
    $length = rand($maxCodeLength / 2, $maxCodeLength + 1);
    $options = strlen($chars);
    $code = '';
    for ($i = 0; $i < $length; $i++) {
        $code .= $chars{rand(0, $options - 1)};
    }
    if (!mysql_query("SELECT * FROM catpcha LIMIT 0,1")) {
        $sql = "CREATE TABLE captcha (text tinytext, hash tinytext, time int)";
        mysql_query($sql);
    }
    $hash = sha1($code);
    $sql = "INSERT INTO captcha (text, hash, time) VALUES ('$code', '$hash'," .
         " " . time() . ")";
    mysql_query($sql);
    $_SESSION['code'] = $code;
    $sql = "DELETE FROM captcha WHERE time < " . (time() - 3600);
    mysql_query($sql);
}

function getCaptchaText($hash) {
    require_once dirname(__FILE__) . '/../../config.php';
    list($userpassword, $serverport) =
            splitString(Config::DATABASE_ACCESS, '@');
    list($user, $password) = splitString($userpassword, ':');
    list($serverport, $dbname) = splitString($serverport, '//');
    list($server, $port) = splitString($serverport, ':');
    mysql_connect($server, $user, $password);
    mysql_select_db($dbname);
    $sql = "SELECT text FROM captcha WHERE hash = '$hash'";
    $result = mysql_query($sql);
    $row = mysql_fetch_array($result);
    return $row['text'];
}

function showCaptcha() {
    list($width, $height, $maxCodeLength, $backgroundColor, $borderColor,
            $colors, $font, $linesNumber) = captchaSettings();
    $code = getCaptchaText($_GET['show']);
    
    list($image, $background, $border, $colors) = prepareImage($width, $height,
            $backgroundColor, $borderColor, $colors);

    prepareCanvas($image, $width, $height, $background, $border);
    drawText($image, $code, $colors, $font, $width, $maxCodeLength);
    drawLines($image, $width, $height, $linesNumber, $colors);

    header('Content-type: image/jpeg');
    imagejpeg($image);
}

function splitString($origin, $splitter) {
    if (strpos($origin, $splitter) === false) {
        return array($origin, '');
    } else {
        $part1 = substr($origin, 0, strpos($origin, $splitter));
        $part2 = substr($origin, strpos($origin, $splitter) +
                strlen($splitter));
        return array($part1, $part2);
    }
}

if (isset($_GET['show'])) {
    showCaptcha();
}
?>
